package OperatOfXML;

import Car.Car.Car;
import Factory.FactoryBuilder;
import ManipullateDatabases.OperatorCType;
import ManipullateDatabases.OperatorCar;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class AnalysisXML {
    private final String inFilePath = "xml/CarElement.xml";
    private Document document = null;

    public AnalysisXML() {
        try {
            this.document = new SAXReader().read(inFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertInSQL() {
        Element root = null;
        List<Element> cars = null;
        Set<String> types = new HashSet<>();
        String typeName = null;
        String carName = null;
        String passenger_size = null;
        String carry_size = null;
        String price = null;
        String temp = null;
        int index = 1;
        try {
            root = document.getRootElement();
            cars = root.elements("car");
            for (Element element : cars) {
                temp = element.attributeValue("type");
                types.add(temp);
            }
            for(String s:types){
                OperatorCType.insert(s);
            }
            for (Element element : cars) {
                carName = element.element("name").getStringValue();
                typeName = element.attributeValue("type");
                if (typeName.equals("卡车")) {
                    carry_size = "0";
                    passenger_size = element.element("passenger").getStringValue();
                } else {
                    if (typeName.equals("货车")) {
                        passenger_size = "0";
                        carry_size = element.element("carry_size").getStringValue();
                    } else {
                        carry_size = element.element("carry_size").getStringValue();
                        passenger_size = element.element("passenger").getStringValue();
                    }
                }
                price = element.element("price").getStringValue();
                OperatorCar.insertCar(carName, typeName, passenger_size, carry_size, price);
            }
        } catch (Exception e) {
            System.out.println("xml文件解析出现错误");
            e.printStackTrace();
        }
    }
}
